package com.SpringMVC.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
	
	FilterConfig filterconfig;
	

	public void init(FilterConfig arg0) throws ServletException {
		 filterconfig=arg0;
		 
	}

	
	
	
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		
		 	HttpServletRequest request = (HttpServletRequest) arg0;  
	       	HttpServletResponse response = (HttpServletResponse) arg1;  
	        String   request_url   =   request.getRequestURI();
	        //System.out.println("整个url的路径名称:"+request_url);
	        String   ctx_path   =   request.getContextPath();
	        //System.out.println("这是为了知道上下文环境路径的输出:"+ctx_path);
	        String targetURL = request_url.substring(ctx_path.length());
	        //System.out.println("截取后的url"+targetURL);
	        HttpSession session = request.getSession(false); 
	        
	        if(!("/jsp/login.jsp".equals(targetURL))){  
	           // System.out.println(targetURL+"ctx_path:"+ctx_path+"request_url:"+request_url);  
	            //在不为登陆页面时，再进行判断，如果不是登陆页面也没有session则跳转到登录页面，  
	            if(session == null){  
	            	
	            	
	                response.sendRedirect("/SpringMVC/jsp/login.jsp");  
	                return;  
	            }else{  
	                //这里表示正确，会去寻找下一个链，如果不存在，则进行正常的页面跳转  
	            	arg2.doFilter(request, response);  
	                return;  
	            }  
	        }else{  
	            //这里表示如果当前页面是登陆页面，跳转到登陆页面  
	        	arg2.doFilter(request, response);  
	            return ;  
	        }
	       
	}

	public void destroy() {
		

	}

	

}
